import update from 'immutability-helper';
import { delay } from 'redux-saga';

export default {
    namespace: '$block',
    state: {},
    reducers: {
        pending(state, { payload }) {
            return update(state, {
                $merge: payload
            });
        }
    },
    effects: {
        *start(action, { put, select, cancelled, call }) {
            const { type, payload, ms = 100 } = action.payload;
            yield call(delay, ms);
            const pending = yield select(state => state.$block[type]);
            if (pending) {
                return;
            }
            yield put({ type: 'pending', payload: { [type]: true } });

            try {
                yield put.resolve({
                    type,
                    payload
                });
            } catch (error) {
                yield put({
                    type: '$error/other',
                    payload: { errmsg: error.message }
                });
            } finally {
                if (yield cancelled()) {
                    // cancel 时执行
                }
            }

            yield put({ type: 'pending', payload: { [type]: false } });
        }
    }
};
